import { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Space,
  Collapse,
  Button,
  message,
  Cascader,
  Form,
  Switch,
  Select,
  Input,
  Table,
  Upload,
  InputNumber,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, {
  ModalForm,
  ProFormGroup,
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormUploadButton,
  ProFormDigit,
  ProFormRadio,
} from '@ant-design/pro-form';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import Editor from '@/components/MyEditor';
import api from '@/services';
import utils from '@/utils';

const normFile = (e: any) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e && e.fileList;
};

export default () => {
  const [skuToggle, setSkuToggle] = useState(false);

  //单规格数据
  const singleSkuData = [
    {
      price: [
        '销售价',
        <ProFormDigit
          name="price"
          width={100}
          min={0}
          rules={[{ required: true }]}
        />,
      ],
      market_price: [
        '划线价',
        <ProFormDigit
          name="market_price"
          width={100}
          min={0}
        />,
      ],
      cost_price: [
        '成本价',
        <ProFormDigit name="cost_price" width={100} min={0} />,
      ],
      stock: [
        '库存',
        <ProFormDigit
          name="goods_stock"
          width={100}
          min={0}
          rules={[{ required: true }]}
        />,
      ],
      goods_stock_alarm: [
        '库存预警',
        <ProFormDigit
          name="goods_stock_alarm"
          width={100}
          min={0}
        />,
      ],
      sku_no: [
        '商品编码',
        <ProFormText placeholder="请输入商品编码" name="sku_no" width={100} />,
      ],
    },
  ];

  //单规格列数据
  const singleSkuColumns = () => {
    let result: any = [],
      [data] = singleSkuData;

    Object.entries(data).forEach((item: any) => {
      let o = {
        title: item[1][0],
        dataIndex: item[0],
        key: item[0],
        render: () => item[1][1],
      };
      result.push(o);
    });

    return result;
  };

  //单规格表格
  const singleSku = (
    <Table
      columns={singleSkuColumns()}
      dataSource={singleSkuData}
      scroll={{ x: true }}
      rowKey={() => 'cnm'}
      pagination={false}
      bordered
    />
  );

  //获取规格数据格式
  const [skuSpec, setSkuSpec] = useState([]);
  const [skuListColChildren, setSkuListColChildren] = useState<any>([]);

  const onFieldsChange = (fields: any) => {
    let target = fields.filter(
      (item: any) =>
        item.name[0] === 'goods_spec_format' && item.name.length === 1,
    )[0];
    if (!target) return;
    if (
      target.value.findIndex(
        (item: any) =>
          item === undefined ||
          Object.keys(item).length !== 2 ||
          item.spec_name === '' ||
          item.value?.length === 0,
      ) >= 0
    )
      return;
    // console.log('target', target);
    setSkuSpec(target.value);

    let children = skuSpec.map((item: any, index) => ({
      title: item.spec_name,
      dataIndex: index + '',
      key: index + '',
    }));

    setSkuListColChildren(children);
  };

  //规格组合
  const specCartesian: any = (arr1: any, arr2?: any) => {
    var result = [];
    var first = arr1.splice(0, 1);
    arr2 = arr2 || [];

    if (arr2.length > 0) {
      for (var i in arr2) {
        for (var j in first[0].value) {
          result.push(arr2[i] + ',' + first[0].value[j]);
        }
      }
    } else {
      for (var i in first[0].value) {
        result.push(first[0].value[i]);
      }
    }

    if (arr1.length > 0) {
      result = specCartesian(arr1, result);
    }

    return result;
  };

  //规格列表数据模型
  const skuListModel = {
    goods_sku: '',
    sku_image: '',
    spec_name: '',
    price: '',
    market_price: '',
    cost_price: '',
    weight: '',
    volume: '',
    stock: '',
    goods_stock_alarm: '',
    sku_no: '',
  };

  //规格列表数据
  const [skuListData, setSkuListData] = useState([]);
  const [form] = Form.useForm();

  //规格列表表头配置
  const skuListColumns = () => {
    let result: any = [],
      titles = [
        'goods_sku 商品规格',
        'sku_image sku图片',
        'spec_name 规格名称',
        'price 销售价',
        'market_price 划线价',
        'cost_price 成本价',
        'weight 重量',
        'volume 体积',
        'stock 库存',
        'goods_stock_alarm 库存预警',
        'sku_no 商品编码',
      ];
    titles.forEach((item: any, index, self) => {
      let [field, title] = item.split(' ');
      let o: any = {
        title,
        dataIndex: field,
        key: field,
        width: '150',
      };

      if (index === 0) {
        o.children = skuListColChildren;

        o.render = () => {
          return {
            props: {
              colSpan: 1,
            },
          };
        };
      } else if (index === 1) {
        o.render = (a: any, b: any, i: any) => {
          return {
            children: (
              <Form.List name={i + ''}>
                {(fields) => {
                  return (
                    <>
                      {fields.map((field) => (
                        <Space
                          key={field.key}
                          style={{ display: 'flex', marginBottom: 8 }}
                          align="center"
                        >
                          <Form.Item
                            {...field}
                            name={[field.name, 'sku_image']}
                            fieldKey={[field.fieldKey, 'sku_image']}
                            valuePropName="fileList"
                            getValueFromEvent={normFile}
                          >
                            <Upload
                              style={{ width: '80px', height: '80px' }}
                              action="http://localhost:7001/shop/upload"
                              headers={{
                                Authorization: `Bearer ${sessionStorage.getItem(
                                  'token',
                                )}`,
                              }}
                              listType="picture-card"
                              maxCount={10}
                            >
                              <div>
                                <PlusOutlined />
                                <div style={{ marginTop: 8 }}>Upload</div>
                              </div>
                            </Upload>
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'spec_name']}
                            fieldKey={[field.fieldKey, 'spec_name']}
                          >
                            <Input
                              style={{ width: '88px' }}
                              placeholder="请输入规格名称"
                            />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'price']}
                            fieldKey={[field.fieldKey, 'price']}
                          >
                            <InputNumber min={0} />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'market_price']}
                            fieldKey={[field.fieldKey, 'market_price']}
                          >
                            <InputNumber min={0} />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'cost_price']}
                            fieldKey={[field.fieldKey, 'cost_price']}
                          >
                            <InputNumber min={0} />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'weight']}
                            fieldKey={[field.fieldKey, 'weight']}
                          >
                            <InputNumber min={0} />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'volume']}
                            fieldKey={[field.fieldKey, 'volume']}
                          >
                            <InputNumber min={0} />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'stock']}
                            fieldKey={[field.fieldKey, 'stock']}
                          >
                            <InputNumber min={0} />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'goods_stock_alarm']}
                            fieldKey={[field.fieldKey, 'goods_stock_alarm']}
                          >
                            <InputNumber min={0} />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            name={[field.name, 'sku_no']}
                            fieldKey={[field.fieldKey, 'sku_no']}
                          >
                            <Input
                              style={{ width: '88px' }}
                              placeholder="请输入商品编码"
                            />
                          </Form.Item>
                        </Space>
                      ))}
                    </>
                  );
                }}
              </Form.List>
            ),
            props: {
              colSpan: self.length - 1,
            },
          };
        };
      } else {
        o.render = () => {
          return {
            props: {
              colSpan: 0,
            },
          };
        };
      }

      result.push(o);
    });
    return result;
  };

  //多规格列表
  const skuList = (
    <Form.Item label="规格列表">
      <Table
        columns={skuListColumns()}
        dataSource={skuListData}
        scroll={{ x: true }}
        rowKey={(r: any) => r.id}
        pagination={false}
        bordered
      />
    </Form.Item>
  );

  //确定添加规格
  const refreshAddSku = () => {
    let result =
      skuSpec.findIndex(
        (item: any) =>
          item === undefined ||
          Object.keys(item).length !== 2 ||
          item.spec_name === '' ||
          item.value?.length === 0,
      ) >= 0;
    if (result) return message.error('请填写完整');
    // console.log(skuSpec);
    let makeUpResult = specCartesian([...skuSpec]); //组合规格
    let data = makeUpResult.map((item: any, index: number) => {
      //生成规格列表
      let goodsSku = item.split(',');
      let model: any = { ...skuListModel };
      model.id = index;
      model.spec_name = item;
      goodsSku.forEach((goodsSkuItem: any, index: number) => {
        model[index] = goodsSkuItem;
      });
      return model;
    });

    setSkuListData(data);

    let initial: any = {};

    data.forEach((item: any, index: number) => {
      initial[index] = [
        {
          sku_image: [],
          spec_name: item.spec_name,
          price: 0,
          market_price: 0,
          cost_price: 0,
          weight: 0,
          volume: 0,
          stock: 0,
          goods_stock_alarm: 0,
          sku_no: '',
        },
      ];
    });

    form.setFieldsValue(initial);
  };

  //多规格表单
  const multiSku = (
    <Row>
      <Col>
        <Form.List name="goods_spec_format">
          {(fields, { add, remove }) => (
            <>
              {fields.map(
                ({ key, name, fieldKey, ...restField }, index, self) => (
                  <Space
                    key={key}
                    style={{ display: 'flex', marginBottom: 8 }}
                    align="baseline"
                  >
                    <Form.Item
                      {...restField}
                      name={[name, 'spec_name']}
                      fieldKey={[fieldKey, 'spec_name']}
                      rules={[{ required: true }]}
                    >
                      <Input placeholder="请输入规格" />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'value']}
                      fieldKey={[fieldKey, 'value']}
                      rules={[{ required: true }]}
                    >
                      <Select
                        placeholder="请输入规格值"
                        style={{ width: '200px' }}
                        mode="tags"
                        tokenSeparators={[',']}
                      />
                    </Form.Item>
                    <MinusCircleOutlined
                      onClick={() => {
                        remove(name);
                        if (self.length !== 1) return;
                        setSkuListData([]);
                        setSkuListColChildren([]);
                        form.setFieldsValue({});
                      }}
                    />
                  </Space>
                ),
              )}
              <Form.Item>
                <Row gutter={5}>
                  <Col>
                    <Button
                      type="primary"
                      onClick={() => add()}
                      icon={<PlusOutlined />}
                    >
                      添加规格
                    </Button>
                  </Col>
                  <Col>
                    {skuSpec.length ? (
                      <Button type="primary" onClick={() => refreshAddSku()}>
                        刷新
                      </Button>
                    ) : (
                      <></>
                    )}
                  </Col>
                </Row>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Col>
    </Row>
  );

  const [goodsContent, setGoodsContent] = useState('');

  //获取商品分类树
  const [categoryOptions, setCategoryOptions] = useState([])
  const getGoodsCategoryTree = async () => {
    const data: any = await api.reqGoodsCategoryTree()
    console.log(data);

    if (data.data.code !== 0) return
    let options = utils.recursionTree(data.data.data, [['category_id', 'value'], ['category_name', 'label']], 3)
    console.log(options);
    setCategoryOptions(options)
  }

  useEffect(() => { getGoodsCategoryTree() }, [])

  const columns = [
    {
      title: '商品信息',
      key: 'goods_info',
      width: 300,
      render: (params: any) => {
        return (
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div style={{ flex: '0 0 50px', height: '50px', marginRight: '5px' }}>
              <img
                style={{ width: '100%', height: '100%' }}
                src={params.goods_image.split(',')[0]}
                alt=""
              />
            </div>
            <div>{params.goods_name}</div>
          </div>
        );
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      render: (params: any) => {
        return <>{`￥${params}`}</>;
      },
    },
    {
      title: '库存',
      dataIndex: 'goods_stock',
    },
    {
      title: '销量',
      dataIndex: 'sale_num',
    },
    {
      title: '状态',
      dataIndex: 'goods_state',
      valueType: 'select',
      filters: true,
      onFilter: true,
      valueEnum: {
        0: {
          text: '已下架',
          status: 'Error',
        },
        1: {
          text: '销售中',
          status: 'Success',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      valueType: 'date',
    },
    {
      title: '操作',
      key: 'controller',
      width: 200,
      valueType: 'option',
      render: (...args: Array<any>) => [
        <a key="extension">推广</a>,
        <a key="edit">编辑</a>,
        <a key="ots">下架</a>,
        <TableDropdown
          key="actionGroup"
          onSelect={() => args[3]?.reload()}
          menus={[
            { key: 'mb_price', name: '会员价' },
            { key: 'records', name: '浏览记录' },
            { key: 'comment', name: '评论' },
            { key: 'copy', name: '复制' },
            { key: 'delete', name: '删除' },
          ]}
        />,
      ],
    },
  ]

  //获取商品列表
  const [page, setPage] = useState({totalRow: 0, totalPage: 0})

  const getGoodsList = async (params?: any, sorter?: any, filter?: any) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    console.log(params, sorter, filter);
    const data: any = await api.reqGoodsList({cur_page: params.current})
    console.log(data);
    
    setPage(data.data.data.page)

    data.data.data.list.forEach((item: any) => {
      item.key = item.goods_id
    });
    console.log(data.data.data.list);

    return {
      data: data.data.data.list,
      success: true,
    }
  }

  return (
    <PageContainer>
      <Collapse defaultActiveKey={['1']}>
        <Collapse.Panel header="操作提示" key="1">
          <ul>
            <li>当前显示的是已经审核通过的商品</li>
            <li>
              如果商家的商品操作违规，平台可以操作违规下架，违规下架的商品需要商家编辑审核之后才能重新上架
            </li>
          </ul>
        </Collapse.Panel>
      </Collapse>
      <ModalForm<{
        name: string;
        company: string;
      }>
        title="添加商品"
        trigger={
          <div style={{padding: '20px 0'}}>
            <Button type="primary">
              <PlusOutlined />
              添加商品
            </Button>
          </div>
        }
        initialValues={{
          price: 0,
          market_price: 0,
          cost_price: 0,
          goods_stock: 0,
          goods_stock_alarm: 0,
          max_buy: 0,
          min_buy: 0
        }}
        onFieldsChange={(_, allFields) => {
          onFieldsChange(allFields);
        }}
        onFinish={async (values: any) => {
          values.goods_content = goodsContent;

          let {
            cost_price,
            goods_content,
            goods_image,
            goods_name,
            goods_state,
            goods_stock_alarm,
            goods_brand,
            category_id,
            introduction,
            is_consume_discount,
            is_free_shipping,
            keywords,
            market_price,
            max_buy,
            min_buy,
            price,
            sku_no,
            goods_stock,
            unit,
            goods_spec_format,
            ...goodsSku
          } = values;

          goods_image = goods_image
            .map((item: any) => item.response.data.path)
            .join(',');

          let len = 0
          for (let i in goodsSku) {
            len++
            goodsSku[i][0].sku_image = goodsSku[i][0].sku_image
              .map((item: any) => item.response.data.path)
              .join(',');
            goodsSku[i] = goodsSku[i][0];
          }

          goodsSku.length = len
          goodsSku = Array.from(goodsSku)



          const data = await api.reqGoodsAdd({
            cost_price,
            goods_content,
            goods_image,
            goods_name,
            goods_state,
            goods_stock_alarm,
            goods_brand,
            category_id,
            introduction,
            is_consume_discount,
            is_free_shipping,
            keywords,
            market_price,
            max_buy,
            min_buy,
            price,
            sku_no,
            goods_stock,
            unit,
            goods_spec_format,
            goodsSku,
          });
          console.log(data);

          message.success('提交成功');
          form.resetFields()
          return true;
        }}
        form={form}
      >
        <ProFormGroup label="基本信息">
          <ProFormText
            name="goods_name"
            width="md"
            label="商品名称"
            placeholder="请输入商品名称"
            rules={[{ required: true }]}
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormTextArea
            name="introduction"
            label="促销语"
            width="lg"
            placeholder="请输入促销语"
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormUploadButton
            name="goods_image"
            label="商品主图"
            max={10}
            rules={[{ required: true }]}
            fieldProps={{
              name: 'files',
              listType: 'picture-card',
              headers: {
                Authorization: `Bearer ${sessionStorage.getItem('token')}`,
              },
            }}
            action="http://localhost:7001/shop/upload"
            tooltip="第一张图片将作为商品主图,支持同时上传多张图片,多张图片之间可随意调整位置；支持jpg、gif、png格式上传或从图片空间中选择，建议使用尺寸800x800像素以上、大小不超过1M的正方形图片，上传后的图片将会自动保存在图片空间的默认分类中，最多上传10张（至少1张）"
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormText
            name="keywords"
            width="md"
            label="关键词"
            placeholder="请输入关键词"
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormSelect
            name="goods_brand"
            width="md"
            label="商品品牌"
            request={async () => {
              const data: any = await api.reqGoodsBrandList()
              return data.data.data.map((item: any) => ({
                label: item.brand_name,
                value: [item.brand_id, item.brand_name].join(',')
              }))
            }}
            placeholder="请选择商品品牌"
          />
        </ProFormGroup>
        <ProFormGroup>
          <Form.Item
            name="category_id"
            label="商品分类"
            style={{ width: '328px' }}
            rules={[{ required: true }]}
          >
            <Cascader options={categoryOptions} />
          </Form.Item>
        </ProFormGroup>
        <ProFormGroup label="价格库存">
          <Form.Item label="启用多规格">
            <Switch
              onChange={(checked) => {
                setSkuToggle(checked);
                if (checked) return;
                setSkuListData([]);
                setSkuListColChildren([]);
                form.setFieldsValue({});
              }}
            />
          </Form.Item>
        </ProFormGroup>
        <ProFormGroup>{skuToggle ? multiSku : singleSku}</ProFormGroup>
        <ProFormGroup>{skuListData.length ? skuList : <></>}</ProFormGroup>
        <ProFormGroup label="配送信息">
          <ProFormRadio.Group
            name="is_free_shipping"
            label="是否免邮"
            initialValue={1}
            options={[
              {
                label: '是',
                value: 1,
              },
              {
                label: '否',
                value: 0,
              },
            ]}
          />
        </ProFormGroup>
        <ProFormGroup label="其他信息">
          <ProFormDigit
            label="限购"
            name="max_buy"
            width="md"
            min={0}
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormDigit
            label="起售"
            name="min_buy"
            width="md"
            min={0}
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormText
            name="unit"
            width="md"
            label="单位"
            placeholder="请输入单位"
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormRadio.Group
            name="goods_state"
            label="是否上架"
            initialValue={1}
            options={[
              {
                label: '是',
                value: 1,
              },
              {
                label: '否',
                value: 0,
              },
            ]}
          />
        </ProFormGroup>
        <ProFormGroup>
          <ProFormRadio.Group
            name="is_consume_discount"
            label="是否参与会员等级折扣"
            initialValue={0}
            options={[
              {
                label: '是',
                value: 1,
              },
              {
                label: '否',
                value: 0,
              },
            ]}
          />
        </ProFormGroup>
        <Form.Item label="商品详情">
          <Editor
            onEditorChange={(ev) => {
              setGoodsContent(ev);
            }}
          />
        </Form.Item>
      </ModalForm>
      <ProTable
        columns={columns}
        request={getGoodsList}
        rowKey="key"
        pagination={{
          showQuickJumper: true,
          pageSizeOptions: ['10', '20', '50', '100'],
          total: page.totalRow
        }}
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}
        dateFormatter="string"
        toolbar={{
          title: '商品列表',
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary">
            批量删除
          </Button>,
          <Button type="primary" key="primary">
            批量上架
          </Button>,
          <Button type="primary" key="primary">
            批量下架
          </Button>,
          <Button type="primary" key="primary">
            批量设置
          </Button>,
        ]}
        rowSelection={{
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          // 注释该行则默认不显示下拉选项
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
        }}
        expandable={{
          expandedRowRender: (params) => {
            return (
              <div>
                {params.skuList.map((item: any) => (
                  <div
                    key={item.sku_id}
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      width: '280px',
                      padding: '5px',
                      margin: '20px 0 20px 100px',
                      border: '1px solid #f0f0f0',
                    }}
                  >
                    <div
                      style={{ flex: '0 0 80px', height: '80px', marginRight: '5px' }}
                    >
                      <img
                        style={{ width: '100%', height: '100%' }}
                        src={item.sku_image.split(',')[0]}
                        alt=""
                      />
                    </div>
                    <div>
                      <div>{item.goods_name}</div>
                      <div>{`规格：${item.spec_name}`}</div>
                      <div>{`价格：￥${item.price}`}</div>
                      <div>{`库存：${item.stock}`}</div>
                      <div>{`销量：${item.sale_num}`}</div>
                    </div>
                  </div>
                ))}
              </div>
            );
          },
        }}
      />
    </PageContainer>
  );
};
